import 'package:efood_multivendor/controller/order_controller.dart';
import 'package:efood_multivendor/controller/product_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/data/model/body/review_body.dart';
import 'package:efood_multivendor/data/model/response/order_details_model.dart';
import 'package:efood_multivendor/data/model/response/order_model.dart';
import 'package:efood_multivendor/data/model/response/product_model.dart';
import 'package:efood_multivendor/helper/date_converter.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';

import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/base/my_text_field.dart';
import 'package:efood_multivendor/view/screens/review/rate_review_screen.dart';
import 'package:efood_multivendor/view/screens/review/widget/delivery_man_widget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class DeliveryManReviewWidget extends StatefulWidget {
  final bool? isFromHome;
  bool isEnabled = true;
  DeliveryManReviewWidget({this.isFromHome});

  @override
  State<DeliveryManReviewWidget> createState() =>
      _DeliveryManReviewWidgetState();
}

class _DeliveryManReviewWidgetState extends State<DeliveryManReviewWidget> {
  final TextEditingController _controller = TextEditingController();
  @override
  void initState() {
    super.initState();
    Get.until((route) => Get.isDialogOpen != true);
  }

  Widget build(BuildContext context) {
    return GetBuilder<OrderController>(builder: (orderController) {
      return GetBuilder<ProductController>(builder: (productController) {
        return Scrollbar(
            child: SingleChildScrollView(
          padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
          physics: BouncingScrollPhysics(),
          child: Center(
              child: orderController.orderDetails == null &&
                      productController.unreviewedOrdersResponse != null
                  ? Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                          SizedBox(
                            height: MediaQuery.of(context).size.height / 4,
                          ),
                          CircularProgressIndicator()
                        ])
                  : SizedBox(
                      width: Dimensions.WEB_MAX_WIDTH,
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: EdgeInsets.all(10),
                              child: Container(
                                child: Column(children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Text('restaurant'.tr + ':'),
                                      SizedBox(
                                        width: 5,
                                      ),
                                      Text(
                                        orderController.orderDetails?.restaurant
                                                ?.name ??
                                            '',
                                        style: TextStyle(
                                            color: Theme.of(context)
                                                .colorScheme
                                                .primary),
                                      )
                                    ],
                                  ),
                                  SizedBox(
                                    height: 1.5.h,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(children: [
                                        Icon(Icons.watch_later, size: 17),
                                        SizedBox(
                                            width: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL),
                                        Text(
                                          DateConverter
                                              .dateTimeStringToDateTime(
                                                  orderController.orderDetails!
                                                      .createdAt!),
                                          style: sfRegular,
                                        ),
                                      ]),
                                      Get.find<ProductController>()
                                                  .unreviewedOrdersResponse!
                                                  .totalSize! >
                                              0
                                          ? Text(
                                              'unreviwed'.tr +
                                                  ":" +
                                                  "${Get.find<ProductController>().unreviewedOrdersResponse!.totalSize}",
                                              style: TextStyle(
                                                  color: Theme.of(context)
                                                      .colorScheme
                                                      .primary),
                                            )
                                          : SizedBox()
                                    ],
                                  ),
                                  SizedBox(
                                    height: 1.2.h,
                                  ),
                                ]),
                              ),
                            ),
                            orderController.orderDetails?.deliveryMan != null
                                ? DeliveryManWidget(
                                    deliveryMan: orderController
                                        .orderDetails!.deliveryMan!)
                                : SizedBox(),
                            SizedBox(height: Dimensions.PADDING_SIZE_LARGE),
                            Container(
                              padding:
                                  EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                              decoration: BoxDecoration(
                                color: Theme.of(context).cardColor,
                                borderRadius: BorderRadius.circular(
                                    Dimensions.RADIUS_SMALL),
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors
                                        .grey[Get.isDarkMode ? 700 : 300]!,
                                    blurRadius: 5,
                                    spreadRadius: 1,
                                  )
                                ],
                              ),
                              child: Column(children: [
                                Text(
                                  'rate_his_service'.tr,
                                  style: sfMedium.copyWith(
                                      color: Theme.of(context).disabledColor),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                SizedBox(height: Dimensions.PADDING_SIZE_SMALL),
                                SizedBox(
                                  height: 30,
                                  child: ListView.builder(
                                    itemCount: 5,
                                    shrinkWrap: true,
                                    scrollDirection: Axis.horizontal,
                                    itemBuilder: (context, i) {
                                      return InkWell(
                                        child: Icon(
                                          productController.deliveryManRating <
                                                  (i + 1)
                                              ? Icons.star_border
                                              : Icons.star,
                                          size: 25,
                                          color: productController
                                                      .deliveryManRating <
                                                  (i + 1)
                                              ? Theme.of(context).disabledColor
                                              : Theme.of(context)
                                                  .colorScheme
                                                  .secondary,
                                        ),
                                        onTap: () {
                                          productController
                                              .setDeliveryManRating(i + 1);
                                        },
                                      );
                                    },
                                  ),
                                ),
                                SizedBox(height: Dimensions.PADDING_SIZE_LARGE),
                                Text(
                                  'share_your_opinion'.tr,
                                  style: sfMedium.copyWith(
                                      color: Theme.of(context).disabledColor),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                SizedBox(height: Dimensions.PADDING_SIZE_LARGE),
                                MyTextField(
                                  maxLines: 5,
                                  capitalization: TextCapitalization.sentences,
                                  controller: _controller,
                                  hintText: 'write_your_review_here'.tr,
                                  fillColor: Theme.of(context)
                                      .disabledColor
                                      .withOpacity(0.05),
                                ),
                                SizedBox(height: 40),
                                Padding(
                                  padding: EdgeInsets.symmetric(
                                      horizontal:
                                          Dimensions.PADDING_SIZE_LARGE),
                                  child: Column(
                                    children: [
                                      !productController.isLoading
                                          ? CustomButton(
                                              buttonText: productController
                                                              .submitDelivList ==
                                                          true &&
                                                      Get.find<ProductController>()
                                                              .unreviewedOrdersResponse!
                                                              .totalSize ==
                                                          0
                                                  ? 'submitted'.tr
                                                  : 'submit'.tr,
                                              onPressed: () async {
                                                if (productController
                                                            .submitDelivList ==
                                                        true &&
                                                    Get.find<ProductController>()
                                                            .unreviewedOrdersResponse!
                                                            .totalSize ==
                                                        0) {
                                                } else {
                                                  if (productController
                                                          .deliveryManRating ==
                                                      0) {
                                                    showCustomSnackBar(
                                                        'give_a_rating'.tr);
                                                  } else {
                                                    FocusScopeNode
                                                        currentFocus =
                                                        FocusScope.of(context);
                                                    if (!currentFocus
                                                        .hasPrimaryFocus) {
                                                      currentFocus.unfocus();
                                                    }
                                                    ReviewBody reviewBody =
                                                        ReviewBody(
                                                      deliveryManId:
                                                          orderController
                                                              .orderDetails
                                                              ?.deliveryMan
                                                              ?.id
                                                              .toString(),
                                                      rating: productController
                                                          .deliveryManRating
                                                          .toString(),
                                                      comment: _controller
                                                              .text.isEmpty
                                                          ? 'No comment'
                                                          : _controller.text,
                                                      orderId: Get.find<
                                                              OrderController>()
                                                          .orderDetails
                                                          ?.id
                                                          .toString(),
                                                    );

                                                    productController
                                                        .submitDeliveryManReview(
                                                            reviewBody)
                                                        .then((message) async {
                                                      if (message.isSuccess) {
                                                        await Get.find<
                                                                ProductController>()
                                                            .getUnreviewedOrdersData()
                                                            .then(
                                                                (value) async {
                                                          showCustomSnackBar(
                                                              message.message,
                                                              isError: false);
                                                          _controller.text = '';
                                                          if (value) {
                                                            if (Get.find<ProductController>()
                                                                        .unreviewedOrdersResponse
                                                                        ?.totalSize !=
                                                                    null &&
                                                                Get.find<ProductController>()
                                                                        .unreviewedOrdersResponse!
                                                                        .totalSize! >
                                                                    0) {
                                                              await Get.find<
                                                                      OrderController>()
                                                                  .getOrderDetails(Get
                                                                          .find<
                                                                              ProductController>()
                                                                      .unreviewedOrdersResponse!
                                                                      .reviewOrders![
                                                                          0]
                                                                      .id
                                                                      .toString());
                                                              if (Get.find<OrderController>()
                                                                          .orderDetails
                                                                          ?.id !=
                                                                      null &&
                                                                  Get.find<OrderController>()
                                                                          .orderDetails
                                                                          ?.id !=
                                                                      Get.find<
                                                                              OrderController>()
                                                                          .orderDetails
                                                                          ?.id) {
                                                                List<Details>
                                                                    _orderDetailsList =
                                                                    [];
                                                                Get.find<
                                                                        OrderController>()
                                                                    .orderDetails
                                                                    ?.details
                                                                    ?.forEach(
                                                                        (orderDetail) {
                                                                  _orderDetailsList
                                                                      .add(
                                                                          orderDetail);
                                                                });
                                                                Get.back();
                                                                Get.back();
                                                              }
                                                            }
                                                          } else {}
                                                        });
                                                      } else {
                                                        showCustomSnackBar(
                                                            message.message);
                                                      }
                                                    });
                                                  }
                                                }
                                              },
                                            )
                                          : Center(
                                              child: CircularProgressIndicator
                                                  .adaptive(
                                                backgroundColor:
                                                    Theme.of(context)
                                                        .colorScheme
                                                        .secondary,
                                              ),
                                            )
                                    ],
                                  ),
                                ),
                              ]),
                            ),
                          ]))),
        ));
      });
    });
  }
}
